﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using NPOI.SS.Formula.Functions;
using ET_DbCommon.Model;
using ET_DbCommon.DAL;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// SceneFile.xaml 的交互逻辑
    /// </summary>
    public partial class SceneFile : UserControl, INotifyPropertyChanged
    {
        public ObservableCollection<SceneFileViewModel> SceneFileList { get; set; } = new ObservableCollection<SceneFileViewModel>();
        bool sign = true;
        string alreadyinlist = "";
        public SceneFile()
        {
            InitializeComponent();
        }
        #region INotifyPropertyChanged 接口实现

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }

        #endregion
        private SceneFileViewModel m_SelectedSceneFile;
        public SceneFileViewModel SelectedSceneFile
        {
            get { return this.m_SelectedSceneFile; }
            set
            {
                this.m_SelectedSceneFile = value;
                this.OnPropertyChanged();
            }
        }
        public class SceneFileViewModel : NotifyPropertyChanged
        {
            private int m_Id;
            public int Id
            {
                get { return this.m_Id; }
                set
                {
                    this.m_Id = value;
                    this.OnPropertyChanged();
                }
            }
            private byte[] m_SceneFile;
            public byte[] SceneFile
            {
                get { return m_SceneFile; }
                set
                {
                    m_SceneFile = value;
                    this.OnPropertyChanged();
                }
            }
            private string m_SceneFileName;
            public string SceneFileName
            {
                get { return m_SceneFileName; }
                set
                {
                    m_SceneFileName = value;
                    this.OnPropertyChanged();
                }
            }
            private string m_UsedQuestions;
            public string UsedQuestions
            {
                get { return m_UsedQuestions; }
                set 
                {
                    m_UsedQuestions = value;
                    this.OnPropertyChanged();
                }
            }
            public SceneFileViewModel(SceneFileModel model)
            {
                this.Id = model.Id;
                this.SceneFile = model.SceneFile;
                this.SceneFileName = model.SceneFileName;
                this.UsedQuestions = model.UsedQuestions;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            List<SceneFileModel> sceneFileModels = new List<SceneFileModel>();
            sceneFileModels = SceneFileDAL.GetAllIgnoreFile();
            if (sceneFileModels != null)
            {
                foreach (var info in sceneFileModels)
                {
                    this.SceneFileList.Add(new SceneFileViewModel(info));
                }
            }
            //questions.ItemsSource = this.questionIdNames;
            this.DataContext = this;
        }


        private void upload_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = "场景文件 (*.json)|*.json";
            openDlg.Multiselect = true;
            if (openDlg.ShowDialog() != true) return;
            List<SceneFileModel> lst = new List<SceneFileModel>();
            alreadyinlist = "";
            for (int i = 0; i < openDlg.FileNames.Count(); i++)
            {
                
                SceneFileModel model = new SceneFileModel();
                model.SceneFileName = System.IO.Path.GetFileNameWithoutExtension(openDlg.FileNames[i]);
                foreach (var modelinlist in SceneFileList)
                {
                    if (model.SceneFileName==modelinlist.SceneFileName)
                    {
                        alreadyinlist = alreadyinlist+ model.SceneFileName+" ";
                    }
                }               
                byte[] buffer = File.ReadAllBytes(openDlg.FileNames[i]);
                model.SceneFile = buffer;
                lst.Add(model);
            }
            if(alreadyinlist!="")
            {
                MessageBox.Show(alreadyinlist+"场景文件已存在，请检查");
                return;
            }           
            SceneFileDAL.Insert(lst);
            this.SceneFileList.Clear();
            this.Window_Loaded(null, null);
        }

        private void delete_Click(object sender, RoutedEventArgs e)
        {
            if (this.SelectedSceneFile == null)
            {
                MessageBox.Show("请选择需要删除的文件名");
                return;
            }
            else
            {
                SceneFileModel model = new SceneFileModel()
                {
                    Id = this.SelectedSceneFile.Id,
                    SceneFileName = this.SelectedSceneFile.SceneFileName,
                };
                SceneFileDAL.Delete(model);
            }
            this.SceneFileList.Clear();
            this.Window_Loaded(null, null);
        }

        private void scrollbar_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (scrollbar == null)
                return;
            double num = Math.Abs((int)(e.Delta / 2));
            double offset = 0.0;
            if (e.Delta > 0)
            {
                sign = false;
                offset = Math.Max((double)0.0, (double)(scrollbar.VerticalOffset - num));
            }
            else
                offset = Math.Min(scrollbar.ScrollableHeight, scrollbar.VerticalOffset + num);
            if (offset != scrollbar.VerticalOffset)
            {
                scrollbar.ScrollToVerticalOffset(offset);
                e.Handled = true;
            }
        }

        private void update_Click(object sender, RoutedEventArgs e)
        {
            if(SelectedSceneFile==null)
            {
                MessageBox.Show("请选择需要更新的文件名");
                return;
            }
            else
            {
                OpenFileDialog openDlg = new OpenFileDialog();
                openDlg.Filter = "场景文件 (*.json)|*.json";
                if (openDlg.ShowDialog() != true) return;
                SceneFileModel model = new SceneFileModel();
                byte[] buffer = File.ReadAllBytes(openDlg.FileName);
                string SceneFileTime1 = openDlg.SafeFileName.Substring(10, 11);
                string SceneFileTime2 = openDlg.SafeFileName.Substring(21, 2);
                model.SceneFileName = SceneFileTime1 + "时" + SceneFileTime2 + "分";
                model.SceneFile = buffer;
                model.Id = this.SelectedSceneFile.Id;
                if(this.SelectedSceneFile.SceneFileName!=model.SceneFileName)
                {
                    MessageBox.Show("场景不一致，请确认");
                    return;
                }
                if (PasswordEquals(buffer,this.SelectedSceneFile.SceneFile))
                {
                    MessageBox.Show("场景文件重复，请检查");
                    return;
                }
                else
                {
                    SceneFileDAL.Update(model);
                    this.SceneFileList.Clear();
                    this.Window_Loaded(null, null);
                }               
            }
        }
        private bool PasswordEquals(byte[] b1, byte[] b2)
        {
            if (b1 == null || b2 == null) return false;
            if (b1.Length != b2.Length) return false;
            for (int i = 0; i < b1.Length; i++)
                if (b1[i] != b2[i])
                    return false;
            return true;
        }

        private void BtnRef_Click(object sender, RoutedEventArgs e)
        {
            this.SceneFileList.Clear();
            this.Window_Loaded(null, null);
        }

        private void Alldelete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxButton msgbutton = MessageBoxButton.OKCancel;
            MessageBoxResult result = System.Windows.MessageBox.Show("是否全部删除？", "提示", msgbutton, MessageBoxImage.Question);
            switch (result)
            {
                case MessageBoxResult.OK:
                    //SceneFileDAL.DeleteAllSceneFile();
                    break;
                case MessageBoxResult.Cancel:
                    break;
            }
        }

        private void download_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedSceneFile == null)
            {
                MessageBox.Show("请选择需要更下载的文件名");
                return;
            }
            System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();
            SceneFileModel scene = new SceneFileModel();
            saveDlg.CheckPathExists = true;
            saveDlg.DefaultExt = ".json";
            saveDlg.Filter = "Json files (*.json)|*.json|All files (*.*)|*.*";
            saveDlg.Title = "请选择一个路径保存为场景文件";
            var scenList = SceneFileDAL.GetSceneFile(SelectedSceneFile.Id);
            foreach (var s in scenList)
            {
                scene.SceneFileName = s.SceneFileName;
                scene.SceneFile = s.SceneFile;
                scene.Id = s.Id;
                scene.UsedQuestions = s.UsedQuestions;
            }
            saveDlg.FileName = scene.SceneFileName;
            var result = saveDlg.ShowDialog();

            try 
            {
                File.WriteAllBytes(saveDlg.FileName, scene.SceneFile);
                MessageBox.Show("下载成功");
            }
            catch(Exception ex)
            {
                MessageBox.Show("下载失败，失败原因："+ex.Message);
            }

        }
    }
}



//}

